package com.hardware.controller.category;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.entity.category.SupplierCategory;
import com.hardware.service.category.SupplierCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.hardware.utils.RedisConstants.CACHE_CATEGORY_CUSTOMER_KEY;
import static com.hardware.utils.RedisConstants.CACHE_CATEGORY_SUPPLIER_KEY;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/supplierCategory")
@Slf4j
public class SupplierCategoryController {
    @Autowired
    private SupplierCategoryService supplierCategoryService;

    /**
     * 新增分类
     * @param supplierCategory
     * @return
     */
    @PostMapping
    @CacheEvict(value = CACHE_CATEGORY_SUPPLIER_KEY, allEntries = true)
    public R<String> save(@RequestBody SupplierCategory supplierCategory){
//        log.info("category:{}",category);
        supplierCategoryService.save(supplierCategory);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = CACHE_CATEGORY_SUPPLIER_KEY,key = "#page +'_'+ #pageSize")
    public R<Page> page(int page,int pageSize){

        return supplierCategoryService.page(page,pageSize);
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = CACHE_CATEGORY_SUPPLIER_KEY, allEntries = true)
    public R<String> delete(Long id){

        supplierCategoryService.remove(id);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     * @param supplierCategory
     * @return
     */
    @PutMapping
    @CacheEvict(value = CACHE_CATEGORY_SUPPLIER_KEY, allEntries = true)
    public R<String> update(@RequestBody SupplierCategory supplierCategory){

        supplierCategoryService.updateById(supplierCategory);

        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类数据
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = CACHE_CATEGORY_SUPPLIER_KEY)
    public R<List<SupplierCategory>> list(){
        //条件构造器
        LambdaQueryWrapper<SupplierCategory> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(SupplierCategory::getSort).orderByDesc(SupplierCategory::getUpdateTime);

        List<SupplierCategory> list = supplierCategoryService.list(queryWrapper);
        return R.success(list);
    }
}
